package cn.peng.stu4teach.pages.home;

import android.app.Application;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.MutableLiveData;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.permissionx.guolindev.PermissionX;
import com.permissionx.guolindev.callback.ExplainReasonCallback;
import com.permissionx.guolindev.callback.ForwardToSettingsCallback;
import com.permissionx.guolindev.callback.RequestCallback;
import com.permissionx.guolindev.request.ExplainScope;
import com.permissionx.guolindev.request.ForwardScope;
import com.youth.banner.Banner;
import com.youth.banner.indicator.RectangleIndicator;

import java.util.ArrayList;
import java.util.List;

import cn.peng.stu4teach.R;
import cn.peng.stu4teach.bizutil.BizConst;
import cn.peng.stu4teach.pages.home.adapter.CommFuncsAdapter;
import cn.peng.stu4teach.pages.home.adapter.ImgBannerAdapter;
import cn.peng.stu4teach.pages.home.adapter.MsgTypeAdapter;
import cn.peng.stu4teach.pages.home.bean.FuncsBean;
import cn.peng.stu4teach.pages.home.bean.MsgTypeBean;
import cn.peng.stu4teach.util.base.BaseFragment;

/**
 * 功用：HomeFragment 中使用的 Vm
 */
public class HomeFmVm extends AndroidViewModel {
    /**
     * 是否正在执行权限请求。true-是，false-否。
     * 可被观察的属性。
     */
    public  MutableLiveData<Boolean> permissionRequesting = new MutableLiveData<>(false);
    /**
     * 是否开启扫码界面
     */
    public  MutableLiveData<Boolean> startQrScan          = new MutableLiveData<>(false);
    private BroadcastReceiver        mBroadcastReceiver;

    public HomeFmVm (@NonNull Application application) {
        super(application);
    }

    /**
     * 初始化 banner 视图
     */
    public void initBanner (Banner pBannerView) {
        // 组织要展示的数据
        List<String> pics = new ArrayList<String>();
        pics.add("https://s21.ax1x.com/2024/06/16/pkwNer8.jpg");
        pics.add("https://s21.ax1x.com/2024/06/16/pkwNuVg.jpg");
        pics.add("https://s21.ax1x.com/2024/06/16/pkwNmqS.jpg");
        pics.add("https://s21.ax1x.com/2024/06/16/pkwNKaQ.png");

        // 设置适配器
        pBannerView.setAdapter(new ImgBannerAdapter(pics));

        // 自定义指示器（图形、颜色、宽度、高度、圆角）
        pBannerView.setIndicator(new RectangleIndicator(getApplication()));
        pBannerView.setIndicatorNormalColorRes(R.color.white_percent50);
        pBannerView.setIndicatorSelectedColorRes(R.color.white);
        int w = SizeUtils.dp2px(12);
        int h = SizeUtils.dp2px(5);
        pBannerView.setIndicatorWidth(w, w);
        pBannerView.setIndicatorHeight(h);
        pBannerView.setIndicatorRadius(h);
    }

    /**
     * 获取用户名称
     * xml 布局文件中通过 vm.userName 引用时，
     * 既可以直接引用 public 的 string 变量- userName；
     * 也可以引用返回值为 String 的 getUserName() 方法（该方法被认为是 userName 的 getter）。
     */
    public String getUserName () {
        return "CnPeng";
    }

    /**
     * 扫码图标被点击了（先请求权限，然后执行扫码）
     */
    public void onQrClick (Context pCtx) {
        permissionRequesting.setValue(true);
    }

    /**
     * 请求相机操作权限
     */
    public void requestPermission (BaseFragment pFm) {
        PermissionX.init(pFm)
                .permissions(android.Manifest.permission.CAMERA)
                .onExplainRequestReason(getExplainRequestReasonCallback())
                .onForwardToSettings(getForwardToSettingsCallback())
                .request(getRequestCallback());
    }

    /**
     * 权限请求回调
     */
    private RequestCallback getRequestCallback () {
        return new RequestCallback() {
            @Override
            public void onResult (boolean allGranted, @NonNull List<String> grantedList, @NonNull List<String> deniedList) {
                if (allGranted) {
                    ToastUtils.showShort("全部权限被允许了");
                    startQrScan.setValue(true);
                } else {
                    String deniedPermissions = String.join(", ", deniedList);
                    ToastUtils.showShort("如下权限被拒绝了：%s", deniedPermissions);
                }
            }
        };
    }

    /**
     * 跳转设置界面的回调
     */
    private ForwardToSettingsCallback getForwardToSettingsCallback () {
        return new ForwardToSettingsCallback() {
            @Override
            public void onForwardToSettings (@NonNull ForwardScope scope, @NonNull List<String> deniedList) {
                scope.showForwardToSettingsDialog(deniedList, "请在设置中允许相机访问权限", "OK", "Cancel");
            }
        };
    }

    /**
     * 请求权限时展示请求原因的回调（现在Apk上架时要求必须明确说明为什么要请求该权限。）
     */
    private ExplainReasonCallback getExplainRequestReasonCallback () {
        return new ExplainReasonCallback() {
            @Override
            public void onExplainReason (@NonNull ExplainScope scope, @NonNull List<String> deniedList) {
                scope.showRequestReasonDialog(deniedList, "扫码功能需要相机权限，否则无法运行。请允许", "OK", "Cancel");
            }
        };
    }

    /**
     * 初始化常用功能的 Rv
     */
    public void initCommFuncsRv (RecyclerView pRvCommFunc) {
        List<FuncsBean> funcItems = getCommFuncItems();

        CommFuncsAdapter adapter = new CommFuncsAdapter();
        pRvCommFunc.setAdapter(adapter);

        adapter.setItems(funcItems);
    }

    /**
     * 获取常用功能列表
     */
    private List<FuncsBean> getCommFuncItems () {
        // 先判断本地有没有数据，有直接取出来，转换，然后返回
        String preDataStr = SPUtils.getInstance(BizConst.SP_NAME_COMM_FUNCS).getString(BizConst.SP_KEY_COMM_FUNCS, "");
        if (!TextUtils.isEmpty(preDataStr)) {
            List<FuncsBean> list = GsonUtils.fromJson(preDataStr, GsonUtils.getListType(FuncsBean.class));
            // 追加 “更多” 按钮的入口
            list.add(new FuncsBean("更多", false));
            return list;
        }

        // 本地没有，组织数据（通常是从服务端请求数据）
        List<FuncsBean> list = new ArrayList<>();
        String[] names = {"门禁录入", "公区验收", "房产验收", "巡更", "巡检", "报事报修", "维修指派"};
        for (int i = 0; i < names.length; i++) {
            FuncsBean bean = new FuncsBean("recordId-" + i, names[i], "", "", true);
            list.add(bean);
        }
        // 将数据存储到本地中
        String commFuncStr = GsonUtils.toJson(list);
        SPUtils.getInstance(BizConst.SP_NAME_COMM_FUNCS).put(BizConst.SP_KEY_COMM_FUNCS, commFuncStr);

        // 追加 “更多” 按钮的入口
        list.add(new FuncsBean("更多", false));
        return list;
    }

    /**
     * 监听本地广播
     */
    public void registerBroadCaseReceiver (CommFuncsAdapter adapter) {
        IntentFilter filter = new IntentFilter();
        filter.addAction(BizConst.BROADCAST_KEY_COMM_FUNC_CHANGED);

        mBroadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive (Context context, Intent intent) {
                if (null == intent) {
                    return;
                }
                String funcsStr = intent.getStringExtra(BizConst.SP_KEY_COMM_FUNCS);
                if (!TextUtils.isEmpty(funcsStr)) {
                    List<FuncsBean> list = GsonUtils.fromJson(funcsStr, GsonUtils.getListType(FuncsBean.class));
                    // 追加 “更多” 按钮的入口
                    list.add(new FuncsBean("更多", false));
                    adapter.setItems(list);
                }
            }
        };

        LocalBroadcastManager manager = LocalBroadcastManager.getInstance(getApplication());
        manager.registerReceiver(mBroadcastReceiver, filter);
    }

    /**
     * 解除广播监听
     */
    public void unregisterBroadCaseReceiver () {
        if (null == mBroadcastReceiver) {
            return;
        }
        LocalBroadcastManager.getInstance(getApplication()).unregisterReceiver(mBroadcastReceiver);
    }

    /**
     * 初始化消息类型的列表（即栏目列表）
     */
    public void initMsgTypeRv (RecyclerView pRv) {
        MsgTypeAdapter adapter = new MsgTypeAdapter();
        pRv.setAdapter(adapter);

        List<MsgTypeBean> msgTypes = getMsgTypes();
        adapter.setItems(msgTypes);
    }

    private List<MsgTypeBean> getMsgTypes () {
        String[] names = {"会议纪要", "公告通知", "制度标准", "红头文件", "公司新闻", "企业通知", "示范文本", "其他"};
        int[] iconResId = {R.drawable.ic_msgtype_huiyijiyao, R.drawable.ic_msgtype_gonggaotongzhi,
                R.drawable.ic_msgtype_zhidubiaozhun, R.drawable.ic_msgtype_hongtouwenjian,
                R.drawable.ic_msgtype_gongsixinwen, R.drawable.ic_msgtype_qiyetongzhi,
                R.drawable.ic_msgtype_shifanwenben, R.drawable.ic_msgtype_qitalanmu};

        List<MsgTypeBean> list = new ArrayList<MsgTypeBean>();
        for (int i = 0; i < names.length; i++) {
            list.add(new MsgTypeBean(names[i], iconResId[i]));
        }
        return list;
    }
}
